//
//  CXEmotionViewCell.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/28.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

let btnCellMargin: CGFloat = 5
let btnBottomMargin: CGFloat = 20

class CXEmotionViewCell: UICollectionViewCell {
    
    /// 缓存所有表情图标
    lazy var emoticons = [CXEmotionButton]()
    /// 表情模型数组
    var emotions: [CXEmotion]? {
        
        didSet {
            
            //先将所有按钮隐藏，这样当按钮个数少于最大个数时 界面只显示实际个数的按钮
            for button in emoticons {
                button.hidden = true
            }
            //进一步封装代码
            for (index, emotion) in emotions!.enumerate() {
                
                let button = emoticons[index]
                button.emotion = emotion
            }
        }
    }
    
    var indexPath: NSIndexPath? {
        
        didSet {
            label.hidden = indexPath!.section != 0
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// 删除按钮
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
        btn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
        return btn
    }()
    /// 防止在手指按住滑动的时候多次创建popView
    private lazy var popView: CXEmotionPopView = {
        let popV = CXEmotionPopView.popView()
        
        return popV
    }()
    /// 底部标签 最近使用cell专用
    private lazy var label: UILabel = {
        let lb = UILabel()
        lb.font = UIFont.systemFontOfSize(14)
        lb.text = "最近使用的表情"
        return lb
    }()
    deinit {
        popView.removeFromSuperview()
    }
}
// MARK: - UI
extension CXEmotionViewCell {
    
    private func setupUI() {
//        backgroundColor = UIColor.redColor()
        
        addEmoticons()
        contentView.addSubview(deleteBtn)
        contentView.addSubview(label)
        
        label.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-5)
        }
        //把手势操作添加到cell的好处：方便管理
        let longpressGes = UILongPressGestureRecognizer(target: self, action: "longPress:")
        addGestureRecognizer(longpressGes)
    }
    private func addEmoticons() {
        
        for _ in 0..<CXEmotionMaxCount {
            
            let button = CXEmotionButton()
            button.titleLabel?.font = UIFont.systemFontOfSize(35)
            //添加点击事件
            button.addTarget(self, action: "emotionBtnClick:", forControlEvents: .TouchUpInside)
            //按钮的内容在 didSet 里面设置
            emoticons.append(button)
            contentView.addSubview(button)
        }
    }
    //设置emoticon的frame
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let iconW:CGFloat = (self.bounds.width - 2 * btnCellMargin) / CGFloat(CXEmotionMaxCol)
        let iconH:CGFloat = (self.bounds.height - btnBottomMargin) / CGFloat(CXEmotionMaxRow)
        for (index, button) in emoticons.enumerate() {
            
            let col = index % CXEmotionMaxCol
            let row = index / CXEmotionMaxCol
            button.frame.origin = CGPoint(x: CGFloat(col) * iconW + btnCellMargin, y: CGFloat(row) * iconH)
            button.frame.size = CGSize(width: iconW, height: iconH)
        }
        //布局删除按钮
        deleteBtn.frame.origin.x = self.bounds.width - iconW - btnCellMargin
        deleteBtn.frame.origin.y = self.bounds.height - iconH - btnBottomMargin
        deleteBtn.frame.size = CGSize(width: iconW, height: iconH)
    }
    
    //根据手势，让按钮的弹出视图做出相应操作
    @objc private func longPress(gesture: UILongPressGestureRecognizer) {
        
        let point = gesture.locationInView(self)
//        var resBtn: CXEmotionButton? = nil
        
        //遍历按钮数组 寻找包含对应位置的按钮
        func buttonToPoint(point: CGPoint) -> CXEmotionButton? {
            for button in emoticons {
                
                if CGRectContainsPoint(button.frame, point) {
                    return button
                }
            }
            return nil
        }
        //如果获取不到指定位置相关的按钮 则返回
        guard let resBtn = buttonToPoint(point) else {
            popView.hidden = true
            return
        }
        //有的页面按钮个数少于20个,从该页面移到下一页时，多余的按钮被隐藏,则手指移到上面时 popView不应该显示
        if resBtn.hidden {
            popView.hidden = true
        }
        
        if popView.superview == nil {
            let window = UIApplication.sharedApplication().windows.last!
            window.addSubview(popView)
        }
        ///  保证手指移动时显示popView
        switch gesture.state {
        case .Began, .Changed:
            popView.hidden = false
            popView.display(resBtn)
        default:
            popView.hidden = true
        }
        
        popView.display(resBtn)
    }
    ///  表情按钮点击事件
    @objc private func emotionBtnClick(button: CXEmotionButton) {
        
        let window = UIApplication.sharedApplication().windows.last!
        window.addSubview(popView)
        //转换坐标 将popView添加到最顶层window上好让popView充分显示。因此对应的坐标也需要转变

        popView.display(button)
        popView.hidden = false
        
        //将表情模型保存 以便更新最近使用表情视图cell. 在这里把这个操作封装在emotionTools中
        CXEmotionTools.sharedTool.saveEmotion(button.emotion)
        
        //将表情模型传入 发送通知观察者去输出内容到textView
        NSNotificationCenter.defaultCenter().postNotificationName(CXEmoBtnDidClickNotification, object: nil, userInfo: ["emotion": button.emotion])
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.popView.removeFromSuperview()
        }

    }
}
